﻿using Api.util;
using Domain;
using NHibernate;
using NHibernate.Mapping;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Api
{
    // 卡片操作类
    public  class CardService :BaseService<Card>
    {
        private static CardService instance;
        private static object _lock = new object();
        private CardService(){ }

        /// <summary>
        /// 获取实体类
        /// </summary>
        /// <returns></returns>
        public static CardService getInstance() {
            if (instance == null)
            {
                lock (_lock)
                {
                    if (instance == null)
                    {
                        instance= new CardService();
                        return instance;
                    }
                }
            }
            return instance;
        }

        /// <summary>
        /// 更具卡号查找卡+公用接口相关的接口的相关信息
        /// </summary>
        /// <param name="card_no"> 卡号</param>
        public object findByCardNo(string card_no) {
            string sql = "SELECT a.id, a.card_no, a.type, a.fingerprint,date_format(b.effect_date,'%Y-%m-%d %H:%i:%s') as effect_date,date_format(b.start_date,'%Y-%m-%d %H:%i:%s') as start_date , b.surplus, b.in_varifycation, b.out_varifycation, b.in_surplus_limt, b.in_surplus_sub, b.in_statistic,b.start_date,b.status,b.free_finger,b.free_finger_varify ,free_finger_varify_time FROM m_card AS a LEFT JOIN m_interface AS b ON a.card_no = b.card_no WHERE a.card_no = ?";
            //卡号不能为空
            if (card_no == null || card_no == "") {
                throw new ArgumentException("card_no 不能为空");
            }
            //查询card 相关信息
            IList list = findListByJoinSql(sql,new object[]{card_no});
            if (list != null && list.Count > 0)
            {
                return list[0];
            } else {
                //卡号不存在
                return null;
            }            
        }

        /// <summary>
        ///根据id 获取 pvalue
        /// </summary>
        /// <param name="card_no"> 卡号</param>
        /// <returns></returns>1 进场  2出场
        public int get_pvalue(int id)
        {
            //最后一次成功的行为
            string sql = "SELECT pvalue from m_system_set where id=? LIMIT 1";
            object o = uniqResult(sql, new object[] { id });
            if (o == null)
            {
                return 0;
            }            
            return int.Parse(o.ToString());
        }

        /// <summary>
        /// 跟据卡号 获取最后一次行为成功状态
        /// </summary>
        /// <param name="card_no"> 卡号</param>
        /// <returns></returns>1 进场  2出场
        public int lastStatusByCard(string card_no)
        {
            //当前最后一次成功的行为
            string sql = "SELECT behavior_type from m_behavior_log where card_no=? and behavior_status=1 ORDER BY create_time DESC LIMIT 1";
        //    string now_date = DateTime.Now.ToString("yyyy-MM-dd")+" 00:00:01";//当前有效
            object o = uniqResult(sql, new object[] { card_no });
            if (o == null)
            {//还没有
                return 0;
            }
            //记录表中的最后一次记录
           return (int)o;
        }

        /**
         *扣次
         */
        public void kouci(string card_no) {
               string now_date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            //扣次sql
               string sql = String.Format("update m_interface SET surplus=surplus-in_surplus_sub,in_statistic=in_statistic+1,last_surplus_sub_time='{0}' where card_no='{1}'", now_date,card_no);
            updateBySql(sql);
        }
        /// <summary>
        /// 进出次数减一，当日进出统计
        /// <param name="card_no"> 卡号</param>
        /// <param name="in_surplus_sub"> 进场后剩余次数减一</param> 0 不减 1减一
        /// </summary>
        public bool inSurplusSubAndStatistic(string card_no)
        {
            if (card_no == null || card_no == "")
            {
                throw new ArgumentNullException("card_no 为空");
            }

            object is_late = uniqResultBySql(String.Format("SELECT create_time from m_interface where card_no='{0}'  and surplus>0  and create_time>str_to_date(last_surplus_sub_time,'%Y-%m-%d %H:%i:%s') LIMIT 1 ", card_no));
            if (is_late != null)
            { //创建时间大于最后一次出来的时间 说明卡被删除过
                Console.WriteLine("---------------被删除的临时卡-----------");                
                return true;
            }

            string now_date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            //次卡扣次延迟时间
            string free_time = uniqResultBySql("select pvalue from m_system_set where id=1").ToString();
            //扣次延迟时间
            object o = uniqResultBySql(String.Format("select date_add(str_to_date(last_surplus_sub_time,'%Y-%m-%d %H:%i:%s'),interval {0} minute) from m_interface where card_no='{1}'", free_time, card_no));
            if (o == null)
            {
                Console.WriteLine("---------------没有设置免扣次时间  开始扣次-----------");
                return true;
            }
            else
            {
                if (now_date.CompareTo(o.ToString()) < 0)//还未到扣次时间
                {
                    //还未到扣次时间
                    Console.WriteLine("---------------还未到扣次时间-----------");
                    Console.WriteLine("---------------扣次时间-----------"+o.ToString());
                    return false;
                }
                else
                {
                    Console.WriteLine("---------------当前时间时间-----------" + now_date);
                    Console.WriteLine("---------------扣次时间时间-----------" + o.ToString());
                    return true;
                }
            }

        }

    }
}
